import datetime
import random

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import subprocess
import ocr_title

# 使用合适的中文字体，例如微软雅黑或黑体
font_path = r'msyhbd.ttc'


tags=["#动画中的快乐你想不到",
     "#经典动漫",
      "#熊出没动漫",
      "#光头强的故事",
        "#熊大熊二",
      "#爱本身没有那么复杂",
    "#熊出没之探险日记"]
class AutoRelease:
    def __init__(self, titles,  descris,tags=tags):
        # 初始化参数并将其存储为实例变量
        self.titles = titles  # 文字标题列表
        self.descris = descris  # 描述
        self.tags = tags  # 标签

    # 快手发布
    '''
    video_path 表示视频的路径
    title 表示需要写在封面的标题
    account_en 是账号的英文名称或者数字,不要使用中文
    '''
    def auto_release_kuaishou(self,video_path,title,account_en):
        # 创建 ChromeOptions，并指定 chrome.exe 的路径
        # 获取当前工作目录
        base_dir = os.getcwd()

        # 指定一个新的用户数据目录
        new_user_data_directory = os.path.join(base_dir, f"{account_en}")
        if not os.path.exists(new_user_data_directory):
            os.makedirs(new_user_data_directory)

        # 创建 ChromeOptions
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={new_user_data_directory}")  # 使用新的用户数据目录
        options.add_argument("profile-directory=Default")
        options.add_argument("--start-maximized")  # 最大化窗口

        # 启动 Chrome
        driver = webdriver.Chrome(options=options)

        try:
            driver.get("https://cp.kuaishou.com/article/publish/video")
        except Exception as e:
            print(f"Failed to load page: {e}")

        time.sleep(10)
        print('开始上传视频.')
        # 视频上传
        file_input = WebDriverWait(driver, 100).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")))

        file_input.send_keys(video_path)
        print('上传完成')

        time.sleep(3)
        try:
            # 等待第三个按钮出现  -- 第三个是合集
            button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.XPATH,
                     "(//div[contains(@class, 'ant-select ant-select-single ant-select-allow-clear ant-select-show-arrow')])[4]")
                )
            )

            print("找到按钮，准备点击。")

            # 点击按钮
            button.click()
            print("合集按钮已被点击。")

            time.sleep(3)
            # 等待并找到第一个具有 ant-select-item-option 类的 div 元素
            first_item = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ant-select-item-option"))
            )

            # 点击该元素
            first_item.click()
            print("已点击活跃选项。")
        except Exception as e:
            print(f"快手发布Error: {e}")

        random_title=''
        # 随机选择一个标题
        if len(self.titles) > 0:
            random_title = random.choice(self.titles)
        print(random_title)
        time.sleep(3)
        descri = random.choice(self.descris)
        # 填写描述
        title_input = WebDriverWait(driver, 150).until(
            EC.element_to_be_clickable((By.ID, "work-description-edit")))
        title_input.send_keys(f"{title} {random_title} {descri} ")
        # 每次加三个标签
        title_input.send_keys("#快成长计划 ")
        time.sleep(2)
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")
        time.sleep(1)
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")
        time.sleep(1)
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")

        # 等待直到特定类名的元素出现-当有预览按钮时,说明上传成功
        preview_header = WebDriverWait(driver, 240).until(
            EC.presence_of_element_located((By.CLASS_NAME, "_preview-header_1ahzu_92"))
        )
        print("找到元素，继续执行下一步。")

        # 发布
        time.sleep(3)
        # 等待并找到具有特定类名并包含"发布"文本的 div 元素
        publish_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH,
                                        "//div[contains(@class, '_button_3a3lq_1')]//div[text()='发布']"))
        )
        # _button_3a3lq_1 _button-primary_3a3lq_60
        # 点击该元素
        publish_button.click()

        print("已点击发布按钮。")

        # 等待 10 秒
        time.sleep(10)


        driver.quit()  # 确保在完成后关闭浏览器


    def auto_release_douyin(self,video_path,title,account_en):

        # 创建 ChromeOptions，并指定 chrome.exe 的路径
        # 获取当前工作目录
        base_dir = os.getcwd()

        # 指定一个新的用户数据目录
        new_user_data_directory = os.path.join(base_dir, f"{account_en}")
        if not os.path.exists(new_user_data_directory):
            os.makedirs(new_user_data_directory)

        # 创建 ChromeOptions
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={new_user_data_directory}")  # 使用新的用户数据目录
        options.add_argument("profile-directory=Default")
        options.add_argument("--start-maximized")  # 最大化窗口

        # 启动 Chrome
        driver = webdriver.Chrome(options=options)

        '''
             作用：发布抖音视频
            '''

        # 进入创作者页面，并上传视频
        driver.get("https://creator.douyin.com/creator-micro/content/upload")
        time.sleep(10)
        # 视频上传
        file_input = WebDriverWait(driver, 100).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")))

        file_input.send_keys(video_path)
        print('上传完成')

        time.sleep(10)

        try:
            # 点击封面
            cover_button = WebDriverWait(driver, 100).until(
                EC.element_to_be_clickable((By.XPATH, "//div[@class='cover-Jg3T4p']"))
            )
            cover_button.click()
            time.sleep(2)
            # 点击竖版按钮
            shuban_btn = WebDriverWait(driver, 100).until(
                EC.element_to_be_clickable((By.XPATH, "//button[@class='semi-button semi-button-primary semi-button-light primary-RstHX_']"))
            )
            shuban_btn.click()
            # 点击完成按钮
            time.sleep(2)
            wancheng_btn = WebDriverWait(driver, 100).until(
                EC.element_to_be_clickable((By.XPATH, "//button[@class='semi-button semi-button-primary semi-button-light primary-RstHX_']"))
            )
            wancheng_btn.click()

        except Exception as e:
            print(f"点击抖音封面Error: {e}")

        time.sleep(3)
        # 等待输入框加载并获取元素
        input_element = WebDriverWait(driver, 100).until(
            EC.visibility_of_element_located((By.XPATH, "//input[@class='semi-input semi-input-default' and @type='text']"))
        )


        # 随机选择一个标题
        random_title = random.choice(self.titles)
        print(random_title)

        input_element.send_keys(f"{title} ")  # 替换为你要设置的文本
        input_element.send_keys(f'{random_title}')
        time.sleep(2)
        # 等待加载 input 元素  标题
        input_element2 = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.CLASS_NAME, 'editor-kit-container'))
        )
        time.sleep(2)
        # 随机选择一个标题
        random_desc = random.choice(self.descris)
        print(random_desc)


        # 设置文本
        input_element2.send_keys(f"{random_desc} ")  # 替换为你要设置的文本
        input_element2.send_keys(f"{random.choice(self.tags)} ")
        time.sleep(1)
        input_element2.send_keys(f"{random.choice(self.tags)} ")
        time.sleep(1)
        input_element2.send_keys(f"{random.choice(self.tags)} ")


        time.sleep(2)

        # 加入活动标识
        try:
            # 等待目标类似结构的 div 元素及其包含“动画”文本的下级 div 加载
            target_element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (
                        By.XPATH,
                        "//div[contains(@class, 'container-BPqaWp activity-right-N1pBMo')]//div[descendant::text()[contains(., '动画')]]"
                    )
                )
            )

            # 点击该元素
            target_element.click()
            time.sleep(3)
        except Exception as e:
            print(f"没有相关活动：{e}")

        try:
            # 加入合集 semi-select-option-list semi-select-option-list-chosen
            # 等待并点击第一个下拉框的 div semi-select select-collection-VQbX7A semi-select-single
            select_div = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.CLASS_NAME, "semi-select.select-collection-nkL6sA")
                )
            )
            select_div.click()  # 点击下拉选择框
            time.sleep(1)
            # 第1个合集,索引从1开始
            index = 1
            # 等待下拉选项出现，并找到第一个选项并点击
            first_option = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(            # semi-select-option collection-option
                    (By.XPATH, "(//div[contains(@class, 'semi-select-option collection-option')])[" + str(index) + "]")
                )
            )
            time.sleep(1)
            first_option.click()
            print('成功点击合集')


        except Exception as e:
            print(f"未找到目标元素，错误信息：{e}")

        time.sleep(20)
        try:
            # 等待并检查是否存在包含"重新上传"文本的 div
            upload_div = WebDriverWait(driver, 280).until(
                EC.visibility_of_element_located(
                    (By.XPATH, "//div[contains(text(), '重新上传')]")  # 使用 XPath 来查找包含文本的 div
                )
            )
        except Exception as e:
            print(f"未找到目标元素，错误信息：{e}")

        # 如果找到了 upload_div，则输出成功信息
        print("上传成功！可以点击发布按钮。")

        # 滚动到底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(4)  # 等待滚动完成


        publish_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 "//button[contains(@class, 'primary-cECiOJ')]")
            )
        )



        # 点击发布按钮
        publish_button.click()

        print("已点击发布按钮。")

        # 等待 10 秒
        time.sleep(10)

        driver.quit()  # 确保在完成后关闭浏览器

    def auto_release_xhs(self,video_path,title,account_en):
        # 创建 ChromeOptions，并指定 chrome.exe 的路径
        # 获取当前工作目录
        base_dir = os.getcwd()

        # 指定一个新的用户数据目录
        new_user_data_directory = os.path.join(base_dir, f"{account_en}")
        if not os.path.exists(new_user_data_directory):
            os.makedirs(new_user_data_directory)

        # 创建 ChromeOptions
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={new_user_data_directory}")  # 使用新的用户数据目录
        options.add_argument("profile-directory=Default")
        options.add_argument("--start-maximized")  # 最大化窗口

        # 启动 Chrome
        driver = webdriver.Chrome(options=options)

        try:
            driver.get("https://creator.xiaohongshu.com/publish/publish?from=menu&target=video")
        except Exception as e:
            print(f"Failed to load page: {e}")


        print('开始上传视频.',video_path)
        # 视频上传
        file_input = WebDriverWait(driver, 150).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")))
        time.sleep(3)
        file_input.send_keys(video_path)
        print('上传完成')

        time.sleep(3)


        random_title=''
        # 随机选择一个标题
        if len(self.titles) > 0:
            random_title = random.choice(self.titles)
        print(random_title)
        time.sleep(3)
        descri = random.choice(self.descris)
        # 填写描述
        title_input = WebDriverWait(driver, 150).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "d-text")))
        title_input.send_keys(f"{title} {random_title} ")

        ql_input = WebDriverWait(driver, 150).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "ql-editor")))
        # 每次加三个标签
        ql_input.send_keys(f"{descri}  ")
        time.sleep(2)
        ql_input.send_keys(f"{random.choice(self.tags).replace('抖音','xhs')} ")
        time.sleep(1)
        ql_input.send_keys(f"{random.choice(self.tags).replace('抖音','xhs')} ")
        time.sleep(1)
        ql_input.send_keys(f"{random.choice(self.tags).replace('抖音','xhs')} ")

        # 等待直到特定类名的元素出现-当有预览按钮时,说明上传成功
        publish_button = WebDriverWait(driver, 240).until(
            EC.presence_of_element_located((By.CLASS_NAME, "publishBtn"))
        )
        print("找到元素，继续执行下一步。")

        # 发布
        time.sleep(3)

        # _button_3a3lq_1 _button-primary_3a3lq_60
        # 点击该元素
        publish_button.click()

        print("已点击发布按钮。")

        # 等待 10 秒
        time.sleep(10)


        driver.quit()  # 确保在完成后关闭浏览器

def get_video_duration(input_video_path):
    command = [
        'ffprobe',
        '-v', 'error',
        '-show_entries', 'format=duration',
        '-of', 'default=noprint_wrappers=1:nokey=1',
        input_video_path
    ]
    print("执行命令:", command)
    result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,encoding='utf-8')

    if result.returncode != 0:
        raise ValueError(f"ffprobe 停止工作，错误信息：{result.stderr}")

    return float(result.stdout.strip())


def parse_time_to_seconds(time):
    """将多种时间格式统一转换为秒数"""
    if isinstance(time, str):
        parts = time.split(':')
        if len(parts) == 3:  # HH:MM:SS
            return int(parts[0]) * 3600 + int(parts[1]) * 60 + int(parts[2])
        elif len(parts) == 2:  # MM:SS
            return int(parts[0]) * 60 + int(parts[1])
        else:  # 纯秒数
            return int(parts[0])
    return int(time)


def clip_video(input_video_path, output_video_path, start_time, end_time,big_title):
    """
    使用 ffmpeg 剪辑指定时间范围的视频
    :param input_video_path: 输入视频路径
    :param output_video_path: 输出视频路径
    :param start_time: 开始时间（HH:MM:SS/MM:SS/秒数）
    :param end_time: 结束时间（格式同上）
    """
    # 统一转换时间格式
    start_sec = parse_time_to_seconds(start_time)
    end_sec = parse_time_to_seconds(end_time)

    # 获取视频真实总时长
    total_duration = get_video_duration(input_video_path)

    # 双重校验逻辑（新增）
    if start_sec >= total_duration:
        raise ValueError(f"开始时间超出视频总时长（总时长：{total_duration}秒）")

    if end_sec > total_duration:
        end_sec = total_duration  # 自动修正为视频末尾（可选）
        # 或者保持严格校验：raise ValueError(f"结束时间超出视频总时长 {total_duration}秒")

    if start_sec >= end_sec:
        raise ValueError("开始时间必须早于结束时间")

    print('开始时间',start_sec,'结束时间',end_sec - start_sec)

    # 构建 ffmpeg 命令（保持不变）
    command = [
        'ffmpeg',
        '-ss', str(start_sec),
        '-i', input_video_path,
         '-to', str(end_sec - start_sec),  # 关键修改：转换为持续时间
        '-vf', f"drawtext=fontfile='{font_path}':text='{big_title}':fontcolor=yellow:fontsize=h/20:x=10:y=10",  # 新增文字滤镜
        '-c:v', 'libx264',
        '-preset', 'fast',
        '-crf', '23',
        '-c:a', 'aac',
        '-avoid_negative_ts', '1',
        output_video_path
    ]

    print("执行命令:", ' '.join(command))
    subprocess.run(command, check=True, encoding='utf-8')


def add_text_as_first_frame_fast(input_video_path, text, output_video_path):
    """
   在视频的第一帧加入标题,这样就会自动变成封面
    """

    subprocess.run([
        "ffmpeg", "-y",
        "-i", input_video_path,  # 输入视频
        "-vf",
        f"drawtext=fontfile='{font_path}':text={text}:fontcolor=yellow:fontsize=h/10:x=(w-text_w)/2:y=(h-text_h)/2:enable='eq(n\\,0)'",
        # 文本居中，第一帧显示
        "-c:v", "libx264",  # 编码为H.264
        "-crf", "23",  # 控制质量
        "-preset", "fast",  # 编码速度
        "-c:a", "copy",  # 保留音频
        output_video_path
    ], check=True,encoding='utf-8')




import os


def read_videos_by_numbers(folder_path, numbers):
    # 获取文件夹中的所有文件
    files = os.listdir(folder_path)

    # 过滤出符合格式的文件
    video_files = {int(file.split('.')[0]): file for file in files if file.endswith('.mp4')}

    # 根据传入的数字选择文件
    selected_files = [video_files[num] for num in numbers if num in video_files]

    return selected_files

def read_videos_by_indices(folder_path, indices):
    # 获取文件夹中的所有文件
    files = os.listdir(folder_path)

    # 过滤出符合格式的文件并进行排序
    video_files = sorted([file for file in files if file.endswith('.mp4')])

    # 根据传入的索引选择文件
    selected_files = [video_files[i] for i in indices if i < len(video_files)]  # 避免索引越界

    return selected_files

# 提取文件中的名称
def extract_name(file_name):
    # 使用 os.path.splitext 去掉文件扩展名
    name_without_extension = os.path.splitext(file_name)[0]
    # 选择空格切割的最后一个元素
    return name_without_extension.split('E')[-1]
def main():
    # 示例用法
    #video_file_path = f'G:\\BaiduNetdiskDownload\\少儿英语动画全集分级\\熊出没大合集\\TV版\\2012 熊出没 老版（104集）720P\\'
    video_file_path = f'G:\\BaiduNetdiskDownload\\少儿英语动画全集分级\\熊出没大合集\\TV版\\2017 熊出没之熊熊乐园 S01（52集）1080P\\'
    folder_path = video_file_path  # 替换为你的文件夹路径
    numbers = [12,13,14,15,16,17]  # 传入的数字列表
    selected_files = read_videos_by_indices(folder_path, numbers)
    print(selected_files)

    
    for file in selected_files:
        # 详情里面加上剧集标记

        print('文件',file)
        str_no=extract_name(file)
        print(str_no)
        ji = f'熊熊乐园{str_no}'
        print("视频处理开始！", datetime.datetime.now())
        video_path = video_file_path+file  # 输入视频路径
        title = ocr_title.extract_text_from_video(video_path,'00:01:28')
        print('标题', title)

        # 输出视频路径，带时间戳
        out_name = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')  # 格式化时间戳
        output_video_path = f'f:\\02剪映\\00Python剪辑\\python\\{title}_{out_name}.mp4'

        print('输入文件是:', video_path)
        print('输出文件是:', output_video_path)

        try:
            input_video = video_path  # 输入视频路径
            watermarked_output = output_video_path  # 添加水印后的输出视频路径
            clip_start_time = '00:01:32'  # 从第30秒开始剪辑
            end_time='00:11:10'
            # 剪辑视频
            clip_video(input_video, watermarked_output, clip_start_time,end_time,ji)
            time.sleep(1)
            print('剪切视频完成')
            # return
            # 添加水印文字
            # add_watermark_text(watermarked_output, watermarked_output_new, title_text, position='top-left')

            # 添加完成之后,将watermarked_output文件删除

            # 创建封面图并添加中心标题
            # cover_img = create_thumbnail(watermarked_output, thumbnail_output, '00:03:00', title_text)  # 提取第3分钟的帧作为封面
            # time.sleep(1)

            watermarked_output_new = f'f:\\02剪映\\00Python剪辑\\python\\{title}_{out_name}_1.mp4'

            add_text_as_first_frame_fast(watermarked_output, title, watermarked_output_new)

            print("给视频加封面完成", watermarked_output_new)
            # 删除水印输出文件
            if os.path.exists(watermarked_output):
                os.remove(watermarked_output)
                print(f"已删除文件: {watermarked_output}")
            else:
                print(f"文件 {watermarked_output} 不存在，无法删除。")

            print("视频处理完成！", datetime.datetime.now())
            print("开始发布", watermarked_output_new)

            # 发三个视频.
            titles = [
                "熊出没",
                "光头强回来了",
                "熊大熊二的故事",
                "熊出没动漫",
                "熊大和熊二",
                "吉吉国王毛毛",
                "熊出没的日常",

            ]

            descris = [
                ji+' 光头强的打开方式', ji+' 童年的快乐时光', ji+' 快乐整个童年', ji+' 光头强和李老板的故事', ji+'一个人和两只熊的故事',ji+' 熊出没来了',ji+' 注意熊出没'
            ]
            # # 初始化自动发布对象
            auto = AutoRelease(titles=titles, descris=descris)
            # 发三个视频.
            auto.auto_release_kuaishou(watermarked_output_new, title, 'User_Data_ks_anxinshuijiao')
            auto.auto_release_kuaishou(watermarked_output_new, title,'User_Data')
            auto.auto_release_douyin(watermarked_output_new, title,'User_Data')
            auto.auto_release_douyin(watermarked_output_new, title, 'User_Data_Qinggan')

            ################ 发布小红书
            auto.auto_release_xhs(watermarked_output_new,title,'user_Data')

            print("视频发布完成！", datetime.datetime.now())

            if os.path.exists(watermarked_output_new):
                os.remove(watermarked_output_new)
                print(f"已删除文件: {watermarked_output_new}")
                print("视频处理完成！", datetime.datetime.now())

        except subprocess.CalledProcessError as e:
            print(f"处理视频时出现错误: {e}")
        except ValueError as ve:
            print(ve)



# 示例使用
if __name__ == "__main__":
    main()

    # file=r'C:\Users\liandyao01\Videos\202106081933-英语朗读.mp4'
    # title ='俺是大侦探(下)'
    # titles=["熊出没"]
    # descris = [
    #     "俺是大侦探(下) 熊出没的日常",
    # ]
    # # # 初始化自动发布对象
    # auto = AutoRelease(titles=titles, descris=descris)
    # # 发三个视频.
    # auto.auto_release_xhs(file, title, 'User_Data_xhs_')


    # add_image_as_first_frame_fast('J:\\202410视频剪辑\\猫和老鼠\\python\\75_20241231_144118_1.mp4',
    #                               '猫和老鼠来了',
    #                               'J:\\202410视频剪辑\\猫和老鼠\\python\\75_20241231_144118_2.mp4')
    #auto_relea
    #
